﻿// //  ********************************************************************************
// //  Copyright (C) 2016 Sebastian Kenter. All rights reserved.
// // 
// //  Name    : PhotonServerProject | PhotonServerFramework | SessionManager.cs
// //  Created : 2016 - 03 - 21 12:50
// //  Modified: 2016 - 04 - 18 09:38
// //  ********************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Util;

namespace PhotonServerFramework.Implementation.Database
{
    public static class SessionManager
    {
        #region Class Property Declarations

        /// <summary>Gets the session factory created from the initialized configuration. The returned factory is thread safe.</summary>
        private static ISessionFactory SessionFactory { get; }

        #endregion

        static SessionManager()
        {
            IEnumerable<Assembly> mappingAssemblies =
                AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith("PhotonServerCommon"));

            SessionFactory = Fluently.Configure()
                .Database(MySQLConfiguration.Standard
                    .ConnectionString(
                        c =>
                            c.Server(DBSettings.Default.DBHost)
                                .Database(DBSettings.Default.DBName)
                                .Username(DBSettings.Default.DBUser)
                                .Password(DBSettings.Default.DBPass)))
                .Mappings(m => mappingAssemblies.ForEach(a => m.FluentMappings.AddFromAssembly(a)))
                .BuildSessionFactory();
        }

        /// <summary>Opens a new session on the existing session factory</summary>
        /// <returns>ready to use ISession instance</returns>
        /// <remarks>
        ///     Dispose this instance after you're done with the instance, so after lazy loading has occurred. The returned
        ///     ISession instance is <b>not</b> thread safe.
        /// </remarks>
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }

        #region Class Member Declarations

        #endregion
    }
}
